import { timeFormat, test, priceFormat } from '@/uni_modules/uview-plus'
import { modal } from "@/plugins"
import { toast } from '@/utils/common'
import { share, service } from '@/utils/config'
import { getMpLogin } from '@/utils/login.js'
// 获取节点信息
export function getNode(query, id) {
  return new Promise((resolve, reject)=>{
  	query.select(id).boundingClientRect(data => {
  	  if(data) {
  		  resolve(data)
  	  } else {
  		  reject('节点错误')
  	  }
  	}).exec()
  })
}
//图片路径
export function imgUrl (url = '') {
	const baseUrl = uni.getStorageSync('tyUrl')
	return url ? url.toString().indexOf('http') > -1 ? url : baseUrl + url : ''
}
//金额转换
export function moneyStr (money) {
	return money || money === 0 ? priceFormat(money, 2) : ''
}
//图片预览
export function previewImg (url, urls = []) {
	if (!url && urls.length === 0) return false
	uni.previewImage({
		current: url,
		urls: Array.isArray(urls) && urls.length > 0 ? urls : [url]
	})
}
//点击复制文字
export function copyText (text) {
	if (text) {
		uni.setClipboardData({
			data: text
		})
	}
}
//拨打电话
export function callPhone (phone) {
	if (phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	}
}
//显示数组某项
export function arrText (arr, value) {
	const filterArr = arr.filter(item => item.value == value)
	return filterArr.length > 0 ? filterArr[0]?.label || filterArr[0]?.text : ''
}
//手机号显示
export function phoneText (phone) {
	return phone ? phone.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3') : ''
}
// 分享微信
export function shareWeixin (params) {
	// #ifdef APP-VUE
	uni.share({
		provider: "weixin",
		scene: "WXSceneSession",
		type: 5,
		miniProgram: {
			id: 'wx6263bd290fb30fc9',
			path: 'pages/index/index',
			type: 0,
			webUrl: 'https://www.tydigit.cn'
		},
		title: params?.title || share.title,
		imageUrl: params?.img || share.img,
		success: function (res) {
			console.log(res)
		},
		fail: function (err) {
			console.log(err)
			uni.$u.toast('分享失败')
		}
	})
	// uni.share({
	// 	provider: "weixin",
	// 	scene: "WXSceneSession",
	// 	type: 0,
	// 	href: params.shareUrl || share.shareUrl,
	// 	title: params?.title || share.title,
	// 	summary: params?.content || share.content,
	// 	imageUrl: params?.img || share.img,
	// 	success: function (res) {
	// 	},
	// 	fail: function (err) {
	// 		toast('分享失败')
	// 	}
	// })
	// #endif
	// #ifdef WEB
	uni.setClipboardData({
		data: params.shareUrl,
		success: function () {
			toast('复制成功请前往浏览器中打开')
		}
	})
	// #endif
}
// 微信客服
export function serviceWeixin (params) {
	// #ifdef APP-VUE
	// uni.share({
	// 	provider: 'weixin',
	// 	scene: 'WXSceneSession',
	// 	openCustomerServiceChat: true,
	// 	corpid: service.wxServiceAppId,
	// 	customerUrl: service.wxServiceUrl,
	// 	success(res) {
	// 		console.log(res)
	// 	},
	// 	fail(err) {
	// 		console.log(err)
	// 	}
	// })
	plus.share.getServices( res => {
		const weixin = res.find(i => i.id === 'weixin')
		if (weixin) {
			weixin.openCustomerServiceChat({
				corpid: service.wxServiceAppId,
				url: service.wxServiceUrl
			}, suc => {
				console.log("参数信息:");
				console.log(service.wxServiceAppId)
				console.log(service.wxServiceUrl)
				console.log(suc)
			}, err => {
				toast('打开微信客服失败')
			})
		} else {
			toast('当前环境不支持该服务')
		}
	})
	// #endif
	// #ifdef MP-WEIXIN
	wx.openCustomerServiceChat({
	  extInfo: {
			url: service.wxServiceUrl
		},
	  corpId: service.wxServiceAppId,
	  success(res) {
			console.log(res)
		},
	  fail(err) {
			console.log(err)
		}
	})
	// #endif
	// #ifdef WEB
	window.location.href = service.wxServiceUrl
	// #endif
}
/**
 * @description 时间差时间戳
 * @param {String|Number} timestamp 时间戳
 * @param {String|Boolean} format 
 * 格式化规则如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
 * @returns {string} 转化后的内容
 */
export function timeFrom(dateString = null, format = 'yyyy-mm-dd') {
	let timestamp = dateString ? Number(new Date(dateString.replace(/-/g, '/')).getTime()) : Number(new Date())
	timestamp = parseInt(timestamp)
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000
	let timer = timestamp - (new Date()).getTime()
	timer = parseInt(timer / 1000)
	let tips = ''
	switch (true) {
		case timer < 86400 && timer > 0:
			tips = timer
			break
		case timer < 1:
			tips = '已过期'
			break
		default:
			tips = `${timeFormat(timestamp, format)}到期`
	}
	return tips
}
/**
 * @description 时间戳
 * @param {String|Number} timestamp 时间戳
 * @param {String|Boolean} format 
 * 格式化规则如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
 * @returns {string} 转化后的内容
 */
export function timestampNum(dateString = null) {
	let timestamp = dateString ? Number(new Date(dateString.replace(/-/g, '/')).getTime()) : (new Date()).getTime()
	timestamp = parseInt(timestamp)
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 13) timestamp /= 1000
	return Math.floor(timestamp)
}
// 页面跳转
const switchTabList = ['pages/index/index', 'pages/category/category', 'pages/car/car', 'pages/mine/mine']
export function gotoPage (url) {
	if (!getMpLogin()) {
		return false
	}
	if (!url) return false
	const isSwitchTab = switchTabList.find(item => url.indexOf(item) > -1)
	if (isSwitchTab) {
		uni.switchTab({
			url: url.startsWith('/') ? url : `/${url}`
		})
	} else {
		uni.navigateTo({
			url: url.startsWith('/') ? url : `/${url}`
		})
	}
}
// 分割数组
export function chunkArray (arr, chunkSize) {
	let result = []
	for (let i = 0; i < arr.length; i += chunkSize) {
			result.push(arr.slice(i, i + chunkSize))
	}
	return result
}
// 地图跳转
export function toMapAPP(latitude, longitude, name) {
	let url = ""
	if (plus.os.name == "Android") {
		//判断是安卓端
		plus.nativeUI.actionSheet({
				//选择菜单
				title: "选择地图应用",
				cancel: "取消",
				buttons: [
					{
						title: "百度地图",
					},
					{
						title: "高德地图",
					},
				],
			},
			function (e) {
				switch (e.index) {
					//下面是拼接url,不同系统以及不同地图都有不同的拼接字段
					case 1:
						url =
							// `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
							`baidumap://map/geocoder?src=andr.baidu.openAPIdemo&address=${name}"`;
						break;
					case 2:
						url =
							// `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=1`;
							`androidamap://arroundpoi?sourceApplication=softname&keywords=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
						break;
					default:
						break;
				}
				if (url != "") {
					url = encodeURI(url)
					//plus.runtime.openURL(url,function(e){})调起手机APP应用
					plus.runtime.openURL(url, function (e) {
						plus.nativeUI.alert("本机未安装指定的地图应用")
					});
				}
			}
		);
	} else {
		// iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
		// 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
		//（如urlschemewhitelist:["iosamap","baidumap"]）
		plus.nativeUI.actionSheet({
				title: "选择地图应用",
				cancel: "取消",
				buttons: [
					// 	{
					// 	title: "腾讯地图"
					// },
					{
						title: "百度地图",
					},
					{
						title: "高德地图",
					},
				],
			},
			function (e) {
				switch (e.index) {
					// case 1:
					// 	url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
					// 	break;
					case 1:
						url = `baidumap://map/geocoder?src=andr.baidu.openAPIdemo&address=${name}"`;
						break;
					case 2:
						url = `androidamap://arroundpoi?sourceApplication=softname&keywords=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
						break;
					default:
						break;
				}
				if (url != "") {
					url = encodeURI(url);
					plus.runtime.openURL(url, function (e) {
						plus.nativeUI.alert("本机未安装指定的地图应用");
					});
				}
			}
		);
	}
}
